package com.zhengxing.jienci.user.service.impl;

import com.zhengxing.jienci.common.pojo.SysUser;
import com.zhengxing.jienci.common.util.DateUtil;
import com.zhengxing.jienci.common.util.IdGenerateUtil;
import com.zhengxing.jienci.user.domain.PointDetail;
import com.zhengxing.jienci.user.domain.PointRule;
import com.zhengxing.jienci.user.mapper.PointDetailMapper;
import com.zhengxing.jienci.user.mapper.PointRuleMapper;
import com.zhengxing.jienci.user.mapper.UserMapper;
import com.zhengxing.jienci.user.service.IPointDetailService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * 积分明细 服务实现类
 * </p>
 *
 * @author yyh
 * @since 2020-12-02
 */
@Service
public class PointDetailServiceImpl extends ServiceImpl<PointDetailMapper, PointDetail> implements IPointDetailService {
	
	
	@Autowired
	private PointDetailMapper pdMapper;
	
	@Autowired
	private PointRuleMapper prMapper;

	@Autowired
	private Redisson redission;
	
	@Autowired
	private UserMapper userMapper;

	@Override
	@Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.READ_COMMITTED)
	public int save(String userId, String operation) {
		String prefix_key = "point:";
		String key = prefix_key + userId + ":" + operation;
		PointRule pointRule = prMapper.selectById(operation);
		Integer num = pointRule.getNum();
		Integer rule = pointRule.getRule();
		Map<String, Object> columnMap = new HashMap<>();
		columnMap.put("user_id", userId);
		columnMap.put("create_time", DateUtil.getNowDate());
		List<PointDetail> pointDetails = pdMapper.selectByMap(columnMap);
		if (pointDetails != null && (rule != 0 && pointDetails.size() > rule + 1)) 
			return 0;
		RLock lock = redission.getLock(key);
		lock.lock();
		pointDetails = pdMapper.selectByMap(columnMap);
		if (pointDetails != null && (rule == 0 || pointDetails.size() < rule + 1)) {
			PointDetail pointDetail = new PointDetail();
			pointDetail.setId(IdGenerateUtil.getId());
			pointDetail.setOperation(pointRule.getOperation());
			pointDetail.setNum(num);
			pointDetail.setUserId(userId);
			pointDetail.setCreateTime(new Date());
			pdMapper.insert(pointDetail);
			if(num > 0) {
				SysUser sysUser = userMapper.selectById(userId);
				sysUser.setIntegral(sysUser.getIntegral() + num);
				userMapper.updateById(sysUser);
			}
		}
		lock.unlock();
		return 0;
	}
}
